package com.alfy.sbdemo.websocketdemo.demo2;

import org.java_websocket.enums.ReadyState;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * web socket client singleton
 */
public class WebSocketClientSingleton {

    /**
     * client
     */
    private static WebSocketClientDemo client;

    /**
     * web socket client singleton
     */
    private WebSocketClientSingleton(){
    }

    /**
     * get instance
     *
     * @return {@link WebSocketClientDemo }
     */
    public static WebSocketClientDemo getInstance(String webSocketUri) throws InterruptedException, URISyntaxException {
        if (client == null || client.isClosed()) {
            // 实例 WebSocketClient 对象，并连接到 WebSocket 服务端
            client = new WebSocketClientDemo(new URI(webSocketUri));
            client.connect();
            // 等待服务端响应
            while (!client.getReadyState().equals(ReadyState.OPEN)) {
                System.out.println("连接中··· 请稍后");
                Thread.sleep(1000);
            }
        }
        return client;
    }

    /**
     * close client
     *
     * @param client client
     */
    public static void closeClient(WebSocketClientDemo client){
        client.close();
    }

    /**
     * main
     *
     * @param args args
     */
    public static void main(String[] args) throws URISyntaxException, InterruptedException {
        // 懒汉模式创建客户端连接
        WebSocketClientDemo webSocketClientDemo = WebSocketClientSingleton.getInstance("ws://localhost:8889/websocket/server1?name=wstest");
        // 客户端发送消息
        webSocketClientDemo.sendMessage("----客户端发送消息啦11-----");
        webSocketClientDemo.sendMessage("----客户端发送消息啦22-----");
        // 关闭连接
        WebSocketClientSingleton.closeClient(webSocketClientDemo);
    }

//    连接中··· 请稍后
//    WebSocketClientDemo open 事件 ~~~
//    已发送消息：----客户端发送消息啦11-----
//    已发送消息：----客户端发送消息啦22-----
//    WebSocketClientDemo close 事件, code: 1000
}